package com.neo.tiny.middle.socket.websocket.util;

import cn.hutool.core.lang.Assert;
import com.neo.tiny.middle.socket.dto.SysWebSocketClientInfo;
import lombok.experimental.UtilityClass;

import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description: 后台用户Websocket工具
 * @Author: yqz
 * @CreateDate: 2023/2/13 23:32
 */
@UtilityClass
public class SysAdminWebSocketSender {

    /**
     * 用户id为key
     */
    public static final ConcurrentHashMap<Long, SysWebSocketClientInfo> SESSION_MAP = new ConcurrentHashMap<>(256);

    public void addClient(Long userId, Session session) {
        SysWebSocketClientInfo clientInfo = new SysWebSocketClientInfo();
        clientInfo.setUserId(userId);
        clientInfo.setSession(session);
        SESSION_MAP.put(userId, clientInfo);
    }

    public void removeClient(Long userId) {

        SESSION_MAP.remove(userId);
    }

    /**
     * 根据客户端id获取客户端会话
     *
     * @param userId 客户端id
     * @return 会话
     */
    public SysWebSocketClientInfo getClientById(Long userId) {

        return SESSION_MAP.get(userId);
    }

    /**
     * 给指定客户端发消息
     *
     * @param userId  客户端id
     * @param content 内容
     */
    public SysWebSocketClientInfo sendMsg(Long userId, String content) {
        SysWebSocketClientInfo clientInfo = getClientById(userId);

        Session session = clientInfo.getSession();
        Assert.notNull(session, "该客户端不在线");
        try {
            session.getBasicRemote().sendText(content);
            // 发送ping
            //PingMessage pingMessage = new PingMessage();
            //session.getBasicRemote().sendPing(pingMessage.getPayload());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return clientInfo;
    }

    /**
     * 获取所有的websocket客户端
     *
     * @return 客户端集合
     */
    public Map<Long, SysWebSocketClientInfo> listAllWebSocketClient() {
        return SESSION_MAP;
    }
}
